package com.paireach.szwolaiyun.service;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.paireach.szwolaiyun.sz_util.SharedPreferencesUtil;
import com.paireach.szwolaiyun.util.BaiDuSimpleLocationHelp;

import java.util.Timer;
import java.util.TimerTask;

import szwolaiyun.paireach.com.szwolaizhuang.net.WayBillRequest;

public class LocationUploadService extends Service {
    private static final String TAG = "LocationUploadService";
    private BaiDuSimpleLocationHelp baiDuSimpleLocationHelp;
    private Timer mTimer;

    private int minute = 1;

    private LocationClient locationClient;
    // 定位时间间隔，设置为0时仅定位一次
    private static int getLocationTime = 0;
    public static final int getLocationSucceed = 1000;
    public static final int getLocationFail = 1003;

    private MyLocationListener listener;

    private MyTimerTask task;

    //执行获取地址的操作
    private class MyTimerTask extends TimerTask{

        @Override
        public void run() {
            locationClient.start();
            locationClient.requestLocation();
        }
    }
    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mTimer = new Timer();
        baiDuSimpleLocationHelp = new BaiDuSimpleLocationHelp();
        LocationClientOption option = new LocationClientOption();
        option.setTimeOut(3000);
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        option.setCoorType("bd09ll");
        option.setScanSpan(getLocationTime);
        // 设置是否需要位置信息
        option.setIsNeedAddress(true);
        // 设置是否使用gps
        option.setOpenGps(true);
        // 设置当gps生效时是否输出gps定位结果
        option.setLocationNotify(true);
        // 设置是否在定位结束后杀死定位服务，设置为true为不杀死
        option.setIgnoreKillProcess(false);
        locationClient = new LocationClient(this);
        locationClient.setLocOption(option);
        listener = new MyLocationListener();
        locationClient.registerLocationListener(listener);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        boolean isStart = intent.getBooleanExtra("start", true);
        if (!isStart) {
            stopSelf();
        }
        if (mTimer != null){
            if (task != null){
                task.cancel();  //将原任务从队列中移除
            }
            task = new MyTimerTask();  // 新建一个任务
            mTimer.schedule(task, 0, minute * 60 * 1000);
        }
        return START_STICKY;
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        mTimer.cancel();
        locationClient.unRegisterLocationListener(listener);
    }

    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case getLocationSucceed:
                    BDLocation location = (BDLocation) msg.obj;
                    new WayBillRequest().saveOrderRunningTrack("",
                            SharedPreferencesUtil.getValue(LocationUploadService.this, SharedPreferencesUtil.USER_PHONE),
                            location.getLongitude(),
                            location.getLatitude(),
                            String.valueOf(location.getSpeed()),
                            String.valueOf(location.getDirection()),
                            String.valueOf(location.getAddress().address),
                            location.getProvince(),
                            location.getCity(),
                            location.getDistrict(), "", 'C');

                    Log.d(TAG,"发送的址信息="+location.getAddrStr());
                    break;
            }
        }
    };

    public class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation arg0) {
            Log.e("0011", "定位：latitude=" + arg0.getLatitude() + "\tlongitude="
                    + arg0.getLongitude());
            Message message = new Message();
            message.what = getLocationSucceed;
            message.obj = arg0;
            handler.sendMessage(message);
            locationClient.stop();

            Log.d(TAG,"定位地址是："+arg0.getAddrStr());
        }
    }
}
